package multi_thread.basic;

/**
 * @author Cheng Jun
 * Description: sleep方法不释放锁
 * @version 1.0
 * @date 2020/2/29 14:56
 * @see Thread#sleep(long)
 */
public class SleepExample {

    public static void main(String[] args) {
        // 创建对象，任何对象都可以 被 synchronized 修饰，获取该对象的对象锁。
        // 但是不要使用线程对象作为对象锁，具体原因请看 Thread.join() 源码注释
        Object lock = new Object();
        Thread thread1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " running");
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + " get lock, and will sleep");
                try {
                    // sleep 方法不会释放任何 对象锁
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                    // e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " sleep over and run over");
            }
        }, "线程1");


        Thread thread2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " running");
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + " get lock, sleeping");
                try {
                    Thread.sleep(2_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " sleep over and run over");
            }
        }, "线程2");

        thread1.start();
        thread2.start();

        // interrupt 强行打断 thread1 的 sleep
        // thread1.interrupt();

    }
}
